import configparser
import time
import psutil
import threading
import os
import tkinter as tk
from tkinter.messagebox import showinfo


iniFile = "config_52pj_pd.ini"
defaultFrequency = 3
class Controller:
    ui: object
    def __init__(self):
        pass
    def init(self, ui):
        self.ui = ui
        self.loadInitialization()
        self.monitor_running = False  # 添加一个新的标志
        self.stop_event = None  # 初始化 stop_event 为 None
        self.ui.tk_input_lzaw4q67.config(validate="focusout", validatecommand=self.frequencyValueVerification, invalidcommand=lambda: showinfo(title="提示", message ="请输入数字！"))

    def frequencyValueVerification(self):
        frequency = self.ui.tk_input_lzaw4q67.get()
        return self.setFrequency(frequency,0)
    def setFrequency(self, frequency,type=0):
        if type == 1:
            frequency = self.ui.tk_input_lzaw4q67.get()
        try:
            frequency = int(frequency)
            if type == 1:
                return frequency
            else:
                self.ui.tk_input_lzaw4q67.delete(0, tk.END)
                self.ui.tk_input_lzaw4q67.insert(0, frequency)
                self.configurationSave('default', 'frequency', frequency)
                return True
        except ValueError:
            self.ui.tk_input_lzaw4q67.delete(0, tk.END)
            self.ui.tk_input_lzaw4q67.insert(0, defaultFrequency)
            self.configurationSave('default', 'frequency', defaultFrequency)
            if type == 1:
                return defaultFrequency
            else:
                return False
    def loadInitialization(self):
        #判断文件是否存在
        if not os.path.exists(iniFile):
            with open(iniFile, 'w') as file:
                file.write("[default]\nprocess_name = \nfrequency = " + str(defaultFrequency))
        config = configparser.ConfigParser()
        config.read(iniFile,encoding='GBK')
        ini_process_name = config.get('default','process_name')
        frequency = config.get('default','frequency')
        self.ui.tk_input_lz86i88e.insert(0,ini_process_name)
        self.setFrequency(frequency,0)

    def startMonitor(self,evt):
        if self.monitor_running == True:
            return # 如果监控已经在运行，则不执行任何操作
        process_name = self.ui.tk_input_lz86i88e.get()
        if process_name == "":
            showinfo(title="提示", message ="未输入进程！")
            return False
        process_name = process_name.replace("，",",")
        self.configurationSave('default', 'process_name', process_name)
        process_name_list = process_name.split(",")
        frequency = self.setFrequency(0,1)
        # 创建一个线程来更新
        self.stop_event = threading.Event()  # 创建一个事件对象
        self.thread = threading.Thread(target=self.update_counter, args=(process_name_list,frequency))
        self.thread.daemon = True
        self.thread.start()

        self.ui.tk_button_lz86i78f.config(state=tk.DISABLED)  # 禁用按钮
        self.monitor_running = True

    def update_counter(self, process_name_list,frequency):
        i = 0
        self.stop_event.clear()
        while not self.stop_event.is_set():  # 检查是否收到停止信号
            current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            for proc in psutil.process_iter(['pid', 'name']):
                if proc.info['name'] in process_name_list:
                    proc.terminate()
                    self.ui.tk_text_lz86hgpy.insert(tk.END, f"{current_time}：{proc.info['name']}已被关闭；进程ID：{proc.pid}。\r\n")
                    self.ui.tk_text_lz86hgpy.see(tk.END)  # 自动滚动到底部
            self.ui.tk_input_lzan99g4.delete(0, tk.END)
            self.ui.tk_input_lzan99g4.insert(0, f"{current_time}：持续监控中...")
            if self.stop_event.is_set():
                break
            # 按钮启用
            if i < 6:
                i += defaultFrequency
            elif i == 6:
                self.ui.tk_button_lz86i78f.config(state=tk.NORMAL,text="停止监控",command=lambda: self.stopMonitor())
                i = 7
            time.sleep(frequency)

    def stopMonitor(self):
        if self.monitor_running:
            self.stop_event.set()  # 设置停止事件
            self.monitor_running = False
            self.ui.tk_button_lz86i78f.config(state=tk.NORMAL, text="开始监控",command=lambda: self.startMonitor(self))
            self.ui.tk_input_lzan99g4.delete(0, tk.END)
            self.ui.tk_input_lzan99g4.insert(0, f"监控已停止")

    #配置保存
    def configurationSave(self,section,key,value):
        config = configparser.ConfigParser()
        config.read('config_52pj_pd.ini',encoding='GBK')
        if not config.has_section(section):  # 判断是否包含指定section
            config.add_section(section)  # 添加section到配置文件
        config.set(section, key, str(value))  # 添加section的key-value
        with open('config_52pj_pd.ini', "w") as f:
            config.write(f)  # 将configparser对象写入.ini类型的文件
